<?php
namespace Admin\Model;
use Think\Model;
class RoleModel extends Model 
{
	protected $insertFields = array('role_name');
	protected $updateFields = array('id','role_name');
	protected $_validate = array(
		array('role_name', 'require', '角色名称不能为空！', 1, 'regex', 3),
		array('role_name', '1,150', '角色名称的值最长不能超过 150 个字符！', 1, 'length', 3),
	);
	public function search($pageSize = 20)
	{
		/**************************************** 搜索 ****************************************/
		$where = array();
		if($role_name = I('get.role_name'))
			$where['role_name'] = array('like', "%$role_name%");
		/************************************* 翻页 ****************************************/
		$count = $this->alias('a')->where($where)->count();
		$page = new \Think\Page($count, $pageSize);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$data['page'] = $page->show();
		/************************************** 取数据 ******************************************/
		/**
		 * SELECT a.*,GROUP_CONCAT(c.pri_name) pri_name From php38_role a LEFT JOIN
php38_role_pri b ON a.id=b.role_id LEFT JOIN php38_privilege c ON b.pri_id=c.id
GROUP BY a.id;
		 */
	     //三张表的查询 role  role_pri  privilege
	     
	    
	}
	public function search1(){
		$data = $this->alias('a')->field('a.*,group_concat(c.pri_name) pri_name')
		->join('left join s50_role_pri b on a.id=b.role_id left join s50_privilege c on b.pri_id = c.id')
		->group('a.id')
		->select();
		return $data;
	}
	// 添加前
	protected function _before_insert(&$data, $option)
	{
	}
	//使用钩子函数  插入之后讲 pri_id  放到 pri_role表里面
	protected function _after_insert($data,$option){
		$pri_id = I('post.pri_id');
		$role_pri_model = D('role_pri');
		foreach($pri_id as $k=>$v){
			$role_pri_model->add(array(
					'role_id'=>$data['id'],
					'pri_id'=>$v,
			));
		}
		//var_dump($id);die();
		
		
		
	}
	// 修改前
	protected function _before_update(&$data, $option)
	{
		$id = I('get.id');
		//获得商品表的权限
		$priId = I('post.pri_id');
		//var_dump($priId);die();
		$role_pri_Model = D('role_pri');
		$role_pri_Model->where(array(
			'role_id' => array('eq',$id),
		))->delete();
		if($priId){
			
			foreach($priId as $k=>$v){
				$role_pri_Model->add(array(
					'role_id'=>$id,
					'pri_id' =>$v,
				));
			}
		}
	}
	// 删除前
	protected function _before_delete($option)
	{
		$rpModel = M('role_pri');
		$rpModel->where(array(
			'role_id' => array('eq', I('get.id')),
		))->delete();
	}
	/************************************ 其他方法 ********************************************/
}